﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfAGVSystem.DBModel;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations;
using Dommel;
using WpfAGVSystem.Common;
using System.Reflection;
using WpfAGVSystem.InterFace;
using System.Data.SqlClient;

namespace WpfAGVSystem.Dapper
{
    public class DapperServer:IDBInterface
    {
     //   LogClass logClass { get; set; }
        public DapperServer()
        {
        //   DapperExtensions.DapperExtensions.DefaultMapper = typeof(CustomPluralizedMapper<>);
            //    logClass = new LogClass("DataProcess");
        }


        public IEnumerable<Task_Entity> SearchTask(Expression<Func<Task_Entity, bool>> exception = null, Expression<Func<TaskType_Entity, bool>> exception2 = null)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Task_Entity> WhereTask()
        {
            string tableName = "Task_Entity";
            string tableName1 = "TaskType_Entity";
            string sql = $"select * from {tableName} left join {tableName1} on {tableName}.TaskType_TaskType={tableName1}.TaskType order by Level desc";
            try
            {
                using (IDbConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    var b = connection.Query<Task_Entity, TaskType_Entity, Task_Entity>(sql, (task_EF, taskType_EF) => { task_EF.TaskType_EF = taskType_EF; return task_EF; });
                    return b;
                }
            }
            catch (Exception ex)
            {
                //GrowlModel.Error("数据查询出现异常！");
               // logClass.Push($"执行SQL语句{sql}报错：{ex.Message}");
                return null;
            }
        }

        //public IEnumerable<Task_Entity> Where(Expression<Func<Task_Entity, bool>> exception = null)
        //{
        //    try
        //    {
        //        using (IDbConnection connection = new SqlConnection(ConfigHelper.DBcon))
        //        {
        //            connection.Open();
        //            var product =  connection.GetAsync<Task_Entity, TaskType_Entity, Task_Entity>(1, (order, line) =>
        //            {
        //                Naive mapping example, in reality it requires more gymnastics
        //                order.OrderLines.Add(line);
        //                return order;
        //            });

            //            // var a = connection.Insert<T>(t);
            //            if (a != null)
            //            {
            //                return null;
            //            }
            //            else
            //            {
            //                return null;
            //            }
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        //  GrowlModel.Error("数据新增出现异常！");
            //        //logClass.Push($"执行SQL语句{sql}报错：{ex.Message}");
            //        return null;
            //    }

            //    //var product = await product.GetAsync<Order, OrderLine, Order>(1, (order, line) =>
            //    //{
            //    //    Naive mapping example, in reality it requires more gymnastics
            //    //    order.OrderLines.Add(line);
            //    //    return order;
            //    //});
            //}

        bool IDBInterface.Add<T>(T t)
        {
            try
            {
                using (IDbConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    connection.Open();
                     var a=  connection.Insert<T>(t);
                    if (a != null)
                    {
                        return true;
                    }
                    else 
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                //  GrowlModel.Error("数据新增出现异常！");
                //logClass.Push($"执行SQL语句{sql}报错：{ex.Message}");
                return false;
            }
        }

        long IDBInterface.Count<T>(Expression<Func<T, bool>> exception)
        {
        
            try
            {
                using (IDbConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    connection.Open();
                    return connection.Count<T>(exception);
                }
            }
            catch (Exception ex)
            {
                //GrowlModel.Error("数据查询出现异常！");
                return 0;
            }

        }

         bool IDBInterface.Delete<T>(Expression<Func<T, bool>> exception)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    bool flag = true;
                    connection.Open();
                    var Temp = connection.Select<T>(exception);
                    if (Temp==null)
                    {
                        connection.Close();
                        return flag;
                    }
                    foreach (var item in Temp)
                    {
                        if (connection.Delete(item))
                        {
                            flag=true;
                            break;
                        } 
                    }
                    connection.Close();
                    return flag;

                }
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        bool IDBInterface.Delete<T>()
        {
            try
            {
                using (IDbConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    connection.Open();
                    return connection.DeleteAll<T>() > 0 ? true : false;                
                }
            }
            catch (Exception ex)
            {          
                return false;
            }
        }

        T IDBInterface.FirstOrDefault<T>(Expression<Func<T, bool>> exception)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    connection.Open();
                    if (exception != null)
                    { 
                        var reult = connection.FirstOrDefault<T>(exception);
                        connection.Close();
                        return reult;
                    }
                    else 
                    {
                        var reult = connection.GetAll<T>().FirstOrDefault();
                        connection.Close();
                        return reult;
                    }
                  
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }



        bool IDBInterface.Update<T>(T t)
        {
            try
            {
                using (IDbConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    connection.Open();
                    return connection.Update<T>(t);
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        IEnumerable<T> IDBInterface.Where<T>(Expression<Func<T, bool>> exception)
        {          
            try
            {
                using (IDbConnection connection = new SqlConnection(ConfigHelper.DBcon))
                {
                    connection.Open();
                    return connection.Select<T>(exception);
                }
            }
            catch (Exception ex)
            {
               
                return null;
            }
        }

      





        /// <summary>
        /// 查询任务列表
        /// </summary>
        /// <returns></returns>
        //public IEnumerable<Task_EF> SelectWhereTasks()
        //{
        //    string tableName = GetTableName<Task_EF>();
        //    string tableName1 = GetTableName<TaskType_EF>();
        //    string sql = $"select * from {tableName} left join {tableName1} on {tableName}.TaskType_TaskType={tableName1}.TaskType";
        //    try
        //    {
        //        using (IDbConnection connection = new SqlConnection(SettingPara.DBConnectStr))
        //        {
        //            var b = connection.Query<Task_EF, TaskType_EF, Task_EF>(sql, (task_EF, taskType_EF) => { task_EF.TaskType_EF = taskType_EF; return task_EF; });
        //            return b;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        GrowlModel.Error("数据查询出现异常！");
        //        logClass.Push($"执行SQL语句{sql}报错：{ex.Message}");
        //        return new List<Task_EF>();
        //    }
        //}










        //public bool ImplementSqls(List<Cache_EF> locations,Task_EF task)
        //{
        //    bool istrue = false;
        //    string sql = null;
        //    using (IDbConnection connection = new SqlConnection(SettingPara.DBConnectStr))
        //    {
        //        connection.Open();
        //        IDbTransaction dbTransaction = connection.BeginTransaction();
        //        try
        //        {
        //            int index = 0;
        //            foreach (var location in locations)
        //            {
        //                sql = UpdateSql<Cache_EF>(location);
        //                index = connection.Execute(sql, null, dbTransaction);
        //                if (index <= 0)
        //                {
        //                    dbTransaction.Rollback();
        //                    return false;
        //                }
        //            }
        //            sql = AddSql<HistoricalTask_EF>();
        //            index = connection.Execute(sql, task.CopyHistoricalTask(), dbTransaction);
        //            if (index <= 0)
        //            {
        //                dbTransaction.Rollback();
        //                return false;
        //            }

        //            sql = DeleteSql<Task_EF>( task.id);
        //            index = connection.Execute(sql, null, dbTransaction);
        //            if (index <= 0)
        //            {
        //                dbTransaction.Rollback();
        //                return false;
        //            }
        //            dbTransaction.Commit();
        //            istrue = true;
        //            return istrue;
        //        }
        //        catch (Exception ex)
        //        {
        //            dbTransaction.Rollback();
        //            GrowlModel.Error("数据更新出现异常！");
        //            logClass.Push($"执行SQL语句{sql}报错：{ex.Message}");
        //            return false;
        //        }
        //        finally
        //        {
        //            connection.Close();
        //        }
        //    }
        //}



     

    }
}
